<template>
  <div class="app-container">
    <el-row type="flex" class="row-bg btn-row" justify="end">
      <el-button class="filter-item" size="mini" v-if="$store.state.user.user_perms.includes('1006')" @click="showModal(null, 'Batch Push')" type="primary">{{$t('orderWithdraw.batch_push')}}</el-button>
      <el-button class="filter-item" size="mini" v-if="$store.state.user.user_perms.includes('903')" @click="exportData" type="primary" icon="el-icon-plus">{{$t("order.download")}}</el-button>
    </el-row>
    <el-collapse>
      <el-collapse-item>
        <div slot="title">
          &nbsp;&nbsp;&nbsp;{{$t('order.click_filter')}}&nbsp;&nbsp;&nbsp;<i class="icon iconfont icon-filter" style="font-size: 10px"></i>
        </div>
        <el-form :inline="true" :model="q" class="demo-form-inline query" label-position="left" >
          <el-form-item :label="$t('order.id')">
            <el-input v-model="q.id" :placeholder="$t('order.id')" prefix-icon="el-icon-edit"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="text" disabled>
              {{this.Timetype?$t('order.created_at'):$t('order.payed_at')}}
            </el-button>
            (<el-button type="text" @click="toggleTimetype">{{$t('order.click_switch')}}</el-button>)
            <el-date-picker v-if="Timetype" v-model="created_at.$gte" value-format="yyyy-MM-dd HH:mm:ss" type="datetime" :placeholder="$t('order.select_datetime')"></el-date-picker>
            <el-date-picker v-else v-model="payed_at.$gte" value-format="yyyy-MM-dd HH:mm:ss" type="datetime" :placeholder="$t('order.select_datetime')"></el-date-picker>
            -<el-date-picker v-if="Timetype" v-model="created_at.$lt" value-format="yyyy-MM-dd HH:mm:ss" type="datetime" :placeholder="$t('order.select_datetime')"></el-date-picker>
            <el-date-picker v-else v-model="payed_at.$lt" value-format="yyyy-MM-dd HH:mm:ss" type="datetime" :placeholder="$t('order.select_datetime')"></el-date-picker>
          </el-form-item>
          <el-form-item :label="$t('order.mch_id')">
            <el-select v-model="q.mch_id" :placeholder="$t('order.select') + $t('order.mch_id')">
              <el-option :label="$t('order.all')" :value=null></el-option>
              <el-option v-for="mch of MchList" :key="mch.id" :label="mch.name" :value="mch.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item :label="$t('order.user_id')">
            <el-input v-model="q.user_id" :placeholder="$t('order.user_id')" prefix-icon="el-icon-edit"></el-input>
          </el-form-item>
          <el-form-item :label="$t('order.justpay_order_no')">
            <el-input v-model="q.out_trade_no" :placeholder="$t('order.justpay_order_no')" prefix-icon="el-icon-edit"></el-input>
          </el-form-item>
          <el-form-item :label="$t('order.status')">
            <el-select v-model.number="q.status" :placeholder="$t('order.select') + $t('order.status')">
              <el-option :label="$t('order.all')" :value=null></el-option>
              <el-option v-for="(statu, index) of OrderStatusArray" :key="index" :label="statu" :value="index"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item :label="$t('order.notify_status')">
            <el-select v-model.number="q.notify_status" :placeholder="$t('order.select') + $t('order.notify_status')">
              <el-option :label="$t('order.all')" :value=null></el-option>
              <el-option v-for="(statu, index) of NotifyStatusArray" :key="index" :label="statu" :value="index"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item :label="$t('order.amount')">
            <el-input v-model="q.total_fee" :placeholder="$t('order.amount')" prefix-icon="el-icon-edit"></el-input>
          </el-form-item>
          <el-form-item :label="$t('order.real_amount')">
            <el-input v-model="q.exact_amount" :placeholder="$t('order.real_amount')" prefix-icon="el-icon-edit"></el-input>
          </el-form-item>
          <el-form-item :label="$t('order.collection_amount')">
            <el-input v-model="q.real_amount" :placeholder="$t('order.collection_amount')" prefix-icon="el-icon-edit"></el-input>
          </el-form-item>
          <el-form-item :label="$t('order.bankrecod_id')">
            <el-input v-model="q.record_id" :placeholder="$t('order.bankrecod_id')" prefix-icon="el-icon-edit"></el-input>
          </el-form-item>
          <el-form-item :label="$t('order.card_name')">
            <el-input v-model="q.bankcard_name" :placeholder="$t('order.receiving_card_name')" prefix-icon="el-icon-edit"></el-input>
          </el-form-item>
          <el-form-item :label="$t('order.pay_type')">
            <el-select v-model.number="q.pay_type" :placeholder="$t('order.select') + $t('order.pay_type')">
              <el-option v-for="(statu, index) of PayTypeArray" :key="index" :label="statu" :value="PayType[index]"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="query">{{$t('order.search')}}</el-button>
            <el-button type="danger" @click="reload">{{$t('orderWithdraw.reset')}}</el-button>
          </el-form-item>
        </el-form>
      </el-collapse-item>
    </el-collapse>
    <el-row>
      <el-col >
        {{$t('order.total_success_order')}}: <span style="color: #f00;line-height: 80px" v-if="listData.total_fee">{{listData.total_fee.toFixed(2)}}</span>{{$t('order.rmb')}}&nbsp;&nbsp;&nbsp;&nbsp;
        {{$t('order.total_collection_amount')}}: <span style="color: #f00;line-height: 40px" v-if="listData.real_amount">{{listData.real_amount.toFixed(2)}}</span>{{$t('order.rmb')}}&nbsp;&nbsp;&nbsp;&nbsp;
        {{$t('order.total_real_arrival')}}: <span style="color: #f00;line-height: 40px" v-if="listData.exact_amount">{{listData.exact_amount.toFixed(2)}}</span>{{$t('order.rmb')}}&nbsp;&nbsp;&nbsp;&nbsp;
        {{$t('order.success_rate')}}: <span style="color: #f00;line-height: 40px" v-if="listData.success_rate">{{listData.success_rate.toFixed(2) }}</span>% &nbsp;&nbsp;&nbsp;
        {{$t('order.record_id_stats')}}: <span style="color: #f00;line-height: 40px" v-if="listData.record_id_stats">{{listData.record_id_stats}}</span>{{$t('order.slice')}}&nbsp;&nbsp;&nbsp;&nbsp;
      </el-col>
    </el-row>
    <el-table :data="listData.list" v-loading.body="listLoading" @sort-change="sortlist" element-loading-text="Loading" stripe border fit highlight-current-row>
       <el-table-column label='Selected' width="40" type="selection">
        <template slot-scope="scope">
          <el-checkbox v-model="scope.row.selected" ></el-checkbox>
        </template>
      </el-table-column>
      <el-table-column prop="id" :label='$t("order.id")' sortable width="170"></el-table-column>
      <el-table-column prop="mch_id" :label='$t("order.mch_id")' sortable width="100"></el-table-column>
      <el-table-column prop="out_trade_no" :label='$t("order.justpay_order_no")' sortable width="170"></el-table-column>
      <el-table-column prop="user_id" :label='$t("order.user_id")' sortable width="150"></el-table-column>
      <el-table-column prop="pay_type" :label='$t("order.pay_type")' sortable width="120" :formatter="PayTypeChange"></el-table-column>
      <el-table-column prop="bankcard_name" :label='$t("order.card_name")' sortable width="120"></el-table-column>
      <!-- <el-table-column prop="bankcard_num" :label='$t("order.card_no")' sortable width="180"></el-table-column> -->
      <el-table-column prop="total_fee" :label='$t("order.amount")' sortable width="110"></el-table-column>
      <el-table-column prop="collection_amount" :label='$t("order.collection_amount")' sortable width="110"></el-table-column>
      <el-table-column prop="real_amount" :label='$t("order.real_amount")' style="text-align:center !important;" sortable width="120"></el-table-column>
      <el-table-column prop="record_id" :label='$t("order.bankrecod_id")' sortable width="130"></el-table-column>
      <el-table-column prop="status" :label='$t("order.status")' width="130">
        <template slot-scope="scope">{{OrderStatusArray[scope.row.status]}}</template>
      </el-table-column>
      <el-table-column prop="notify_status" :label='$t("order.notify_status")' width="100">
        <template slot-scope="scope">{{NotifyStatusArray[scope.row.notify_status]}}</template>
      </el-table-column>
      <el-table-column prop="notify_count" :label='$t("order.notify_count")' sortable width="110"></el-table-column>
      <!--<el-table-column prop="notify_url" label='回调地址' sortable width="300"></el-table-column>-->
      <el-table-column prop="payed_at" :label='$t("order.payed_at")' sortable width="100"></el-table-column>
      <el-table-column prop="created_at" :label='$t("order.created_at")' sortable width="100"></el-table-column>
      <!--<el-table-column prop="notified_at" label='通知时间' sortable width="180"></el-table-column>-->
      <el-table-column prop="updated_at" :label='$t("order.updated_at")' sortable width="100"></el-table-column>
      <el-table-column :label='$t("order.action")' width="140" fixed="right">
        <template slot-scope="scope">
          <el-button type="text" v-if="$store.state.user.user_perms.includes('902')" @click="fresh(scope.row.id)">{{$t("order.refresh")}}</el-button>
          <el-button type="text" v-if="$store.state.user.user_perms.includes('904')" @click="edit(scope.row)">{{$t("order.edit")}}</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination">
      <el-pagination  @size-change="handleSizeChange" @current-change="handleCurrentChange"
                      :current-page="q.$page" :page-sizes="$store.state.app.pageSizeArr"
                      :page-size="q.$size"
                      layout="total, sizes, prev, pager, next, jumper"
                      :total="listData.total_count">
      </el-pagination>
    </div>    
    <edit-order :modalOrderData="modalOrderData" @ok="modalOk"></edit-order>
    <order-batch-modal :modalOrderData="modalOrderData" @ok="modalOk"></order-batch-modal>
  </div>
</template>

<script>
  import { getOrderList, OrderFresh, getMchList, pushWithdrawOrder } from '@/api/merchant'
  import {queryFilter} from '@/utils/patch'
  import editOrder from './editOrder'
  import { json2excel } from 'js2excel';
  import { jsonKeyToTitleCase } from '@/utils/index'
  import orderBatchModal from './orderBatchModal'

  export default {
    components: { editOrder, orderBatchModal },    
    data() {
      return {
        listData: {},
        created_at: {},
        payed_at: {},
        MchList: [],
        PayType: ['qr_alipay', 'link_alipay', 'cloud_flash', 'scan_code'],
        Timetype: true,
        q: {$size: 30, $page: 1},
        listLoading: true,
        modalOrderData: {
          selectedOrder: {},
          title: 'View Order',
          action: 'View',
          show: false,
          cancelTitle: 'Cancel',
          batch: false,
          batchOrder: [],          
          batchHeader: '',
          batchIcon: '',
          NotifyStatusArray: [],
          PayTypeArray: [],
          current_status: ''
        }
      }
    },
    created() {
      this.getList()
      this.getMchList()
    },
    deactivated(){
      this.listLoading = false
    },
    computed: {
      OrderStatusArray: function() {
        return [this.$t('order.unpaid'), 
                this.$t('order.failed'), 
                this.$t('order.success'), 
                this.$t('order.timeout'),
                this.$t('order.manual_success')]
      },
      NotifyStatusArray: function() {
        return [this.$t('order.notify_none'), 
                this.$t('order.notify_failed'), 
                this.$t('order.notify_success')]
      },
      PayTypeArray: function() {
        return [this.$t('order.qr_alipay'),
          this.$t('order.link_alipay'),
          this.$t('order.cloud_flash'),
          this.$t('order.scan_code')]
      }
    },
    methods: {
      query(){
        this.getList()
      },
      reload() {
        this.created_at = {}
        this.payed_at = {}
        this.q = {$size: 30, $page: 1}
        this.getList()
      },
      sortlist(sort){
        this.q.$orderby = sort.prop
        this.getList()
      },
      handleSizeChange (val) {
        this.q.$size = val
        this.getList()
      },
      handleCurrentChange (val) {
        this.q.$page = val
        this.getList()
      },
      PayTypeChange(row) {
        if(row.pay_type === 'qr_alipay') {
          return this.$t('order.qr_alipay')
        } else if(row.pay_type === 'link_alipay') {
          return this.$t('order.link_alipay')
        } else if(row.pay_type === 'cloud_flash') {
          return this.$t('order.cloud_flash')
        } else if(row.pay_type === 'scan_code') {
          return this.$t('order.scan_code')
        }else {
          return this.$t('order.unknow')
        }
      },
      fresh(id) {
        let body = {}
        body.id = id
        OrderFresh(body).then(res => {
          if (res.status === 0) {
            this.$message.success(this.$t('order.refresh_success'))
          } else {
            this.$message.error(this.$t('order.refresh_success'))
          }
          this.getList()
        })
      },
        showModal(order, action) {
          let selectedOrders;
          this.modalOrderData.batch = false;
          this.modalOrderData.batchOrder = [];
          switch (action) {
            case 'Push':
                this.push(order)
                break;
      
            case 'Batch Push':
                selectedOrders = this.listData.list.filter(order => order.selected);
                if(selectedOrders.length <= 0) {
                  this.$message({type: 'warning', message: this.$t('orderWithdraw.batch_select') + this.$t('orderWithdraw.' + action.toLowerCase().replace(' ', '_'))})
                  return;
                }
                
                this.modalOrderData.title = `${action} Order`;
                this.modalOrderData.action = action;
                this.modalOrderData.show = true;
                this.modalOrderData.cancelTitle = 'Cancel';
                this.modalOrderData.batch = true;
                this.modalOrderData.batchOrder = selectedOrders;
                this.modalOrderData.batchHeader = 'Do you want to continue push the following Orders?';
                this.modalOrderData.batchIcon = 'fa fa-mail-forward';
                this.modalOrderData.okTitle = action
                break;
        }
      },
      modalOk(evt) {
        switch (this.modalOrderData.action) {
            case 'View':
                break;
            case 'Edit':
                this.getList()
                break;
            case 'Batch Assign':
            case 'Batch Push':
                this.getList()
                break;
            case 'Push':
                break;
        }
      },
      push (order) {
        this.$confirm(this.$t('orderWithdraw.push_confirm') + ` ${order.id}？`, this.$t('orderWithdraw.push'), {
            confirmButtonText: this.$t('orderWithdraw.confirm'),
            cancelButtonText: this.$t('orderWithdraw.cancel'),
            type: 'warning'
        }).then(() => {
          let data = {order_id: order.id}
          pushWithdrawOrder(data).then(res => {
              if (res.status === 0) {
                  this.$message({
                      type: 'success',
                      message: this.$t('orderWithdraw.push_successful')
                  })
                  this.getList()
              }
          })
        }).catch(() => {
            this.$message({
                type: 'info',
                message: this.$t('orderWithdraw.cancelled')
            })
        })
      },
      toggleTimetype() {
        if (this.Timetype) {
          this.created_at = {}
          delete this.q.created_at
          this.Timetype = !this.Timetype
        } else {
          this.payed_at = {}
          delete this.q.payed_at
          this.Timetype = !this.Timetype
        }
      },
      handleTime() {
        if (this.created_at.$gte || this.created_at.$lt) {
          this.q.created_at = {}
          if(this.created_at.$gte) {
            this.q.created_at.$gte = this.created_at.$gte
          }
          if(this.created_at.$lt) {
            this.q.created_at.$lt = this.created_at.$lt
          }
        }
        if (this.payed_at.$gte || this.payed_at.$lt) {
          this.q.payed_at = {}
          if(this.payed_at.$gte) {
            this.q.payed_at.$gte = this.payed_at.$gte
          }
          if(this.payed_at.$lt) {
            this.q.payed_at.$lt = this.payed_at.$lt
          }
        }
      },
      exportData() {
        this.getList(true)
      },
      getList(isDownload = false) {
        this.handleTime()
        let params = Object.assign({
          $orderby: '-id'
        }, this.q)

        if(isDownload){
          params['$size'] = 9999999999
        }

        let queryObj = queryFilter(params)
        this.listLoading = true
        getOrderList(queryObj).then(res => {
          if (res.status === 0) {
            if(isDownload){
              this.listLoading = false
              let orders = [...res.data.list]
              let downloadData = orders.map(order => ({ 
                  id: order.id,
                  mch_id: order.mch_id,
                  mch_order_no: order.out_trade_no,
                  user_id: order.user_id,
                  pay_type: order.pay_type,
                  bankcard_name: order.bankcard_name,
                  bankcard_no: order.bankcard_num,
                  real_amount: order.real_amount,
                  total_fee: order.total_fee,
                  bank_card_record_id: order.record_id,
                  status: this.OrderStatusArray[order.status],
                  payed_at: order.payed_at,
                  created_at: order.created_at,
                  updated_at: order.updated_at
              }));
              var exportData = jsonKeyToTitleCase(downloadData)
              json2excel({ data: exportData, name: 'Order List', formateDate: 'yyyy/mm/dd' })
            } else {
              this.listLoading = false
              this.listData = res.data
            }
          }
        })
      },
      getMchList(){
        getMchList({$size: -1}).then(res => {
          if (res.status === 0) {
            this.MchList = res.data.list
          }
        })
      },
      edit(order){
          this.modalOrderData.selectedOrder = {...order};
          this.modalOrderData.selectedOrder.mch_name = ''
          this.modalOrderData.selectedOrder.status = this.OrderStatusArray[order.status]
          this.modalOrderData.selectedOrder.notify_status = order.notify_status
          this.modalOrderData.title = this.$t('order.edit')
          this.modalOrderData.action = 'Edit';
          this.modalOrderData.show = true;
          this.modalOrderData.cancelTitle = this.$t('order.cancel');
          this.modalOrderData.okTitle = this.$t('order.save');
          this.modalOrderData.NotifyStatusArray = this.NotifyStatusArray
          this.modalOrderData.PayTypeArray = this.PayTypeArray
          this.modalOrderData.current_status = order.status
      }
    }
  }

  export const enOrder = {
    // General
    loading: 'loading',
    total_success_order: 'Total Application Amount',
    total_collection_amount: 'Total Collection Amount',
    total_real_arrival: 'Total Exact Amount',
    click_filter: 'Click to filter',
    all: 'All',
    confirm: 'OK',
    rmb: 'RMB',
    success_rate: 'Success Rate',
    record_id_stats: 'Make Up',
    slice: 'Slice',

    // Search and Filters
    select: 'Please choose ',
    click_switch: 'Click to switch',
    select_datetime: 'Selecte date and time',

    // Table
    id: 'Hydra ID',
    mch_id: 'Company',
    justpay_order_no: 'JP Order No',
    user_id: 'User ID',
    card_name: 'Card Code',
    card_no: 'Account No',
    amount: 'Application Amount',
    real_amount: 'Exact Amount',
    bankrecod_id: 'Bank Record ID',
    status: 'Order Status',
    notify_status: 'Notify Status',
    notify_count: 'Notify Count',
    payed_at: 'Payed At',
    created_at: 'Created At',
    updated_at: 'Updated At',
    action: 'Action',
    collection_amount: 'Collection Amount',

    // Action Link and Buttons
    search: 'Search',
    reset: 'Reset',
    refresh: 'Refresh',
    download: 'Download',

    // Order Status
    unpaid: 'Unpaid',
    failed: 'Failed',
    success: 'Success',
    timeout: 'Timeout',
    manual_success: 'Manual Success',

    // Notify Status
    notify_none: 'None',
    notify_success: 'Success',
    notify_failed: 'Failed',

    // Pay Type
    qr_alipay: 'qr_alipay',
    link_alipay: 'link_alipay',
    cloud_flash: 'cloud_flash',
    scan_code: 'scan_code',
    unknow: 'Unknow',

    // Messages
    receiving_card_name: 'Receiving card name',
    receiving_card_no: 'Receiving card no',
    refresh_success: 'Refresh successfully',
    refresh_failed: 'Refresh failed',
    edit: 'Edit',
    cancel: 'Cancel',
    operator: 'Operator',
    notes: 'Notes',
    save: 'Save',
    note_warning: 'Please enter a note',
    edit_success: 'Edited Successfully',
    edit_failed: 'Edit failed',
    pay_type: 'Pay type'
  }

  export const zhOrder = {
    // General
    loading: 'loading',
    total_success_order: '成功下单金额总计',
    total_real_arrival: '真实到账金额总计',
    total_collection_amount: '总收款金额',
    click_filter: '点击筛选',
    all: '所有',
    confirm: '确定',
    rmb: '元',
    save: '确定',
    success_rate: '成功率',
    record_id_stats: '补单',
    slice: '单',

    // Search and Filters
    select: '请选择',
    click_switch: '点击切换',
    select_datetime: '选择日期时间',

    // Table
    id: 'Hydra ID',
    mch_id: '公司',
    justpay_order_no: 'JP订单号',
    user_id: '用户ID',
    card_name: '银行卡名称',
    card_no: '银行卡号',
    amount: '申请金额',
    real_amount: '实际金额',
    bankrecod_id: '银行记录ID',
    status: '订单状态',
    notify_status: '回调状态',
    notify_count: '回调次数',
    payed_at: '到账时间',
    created_at: '创建时间',
    updated_at: '更新时间',
    action: '操作',
    collection_amount: '收款金额',

    // Action Link and Buttons
    search: '查询',
    reset: '重置',
    refresh: '刷新',
    download: '导出订单',

    // Order Status
    unpaid: '未支付',
    failed: '支付失败',
    success: '支付成功',
    timeout: '超时',
    manual_success: '人工补单',

    // Notify Status
    notify_none: '未回调',
    notify_success: '回调成功',
    notify_failed: '回调失败',

    // Pay Type
    qr_alipay: '宝到卡',
    link_alipay: '链接付',
    cloud_flash: '云闪付',
    scan_code: '扫码付',
    unknow: '未知',

    // Messages
    receiving_card_name: '收款银行名称',
    receiving_card_no: '收款银行卡号',
    refresh_success: '刷新成功',
    refresh_failed: '刷新失败',
    edit: '编辑',
    cancel: '取消',
    operator: '操作者',
    notes: '备注',
    note_warning: '请输入备注',
    edit_success: '编辑成功',
    edit_failed: '编辑失败',
    pay_type: '支付方式'
  }
</script>
